const User = require('../models/user')
const Auth = require('../../middlewares/auth.js')
const { LOGIN_TYPE } = require('../lib/enum')
class AuthService {
  // 注册
  static async Register(requestParams) {
    const user = {
      account: requestParams.get('body.account'),
      email: requestParams.get('body.email'),
      password: requestParams.get('body.password1'),
      nickname: requestParams.get('body.nickname'),
    }
    await User.sync()
    await User.create(user)
  }

  static async Login(requestParams) {
    let token
    const account = requestParams.get('body.account')
    const secret = requestParams.get('body.secret')
    switch (+requestParams.get('body.type')) {
      case LOGIN_TYPE.USER_EMAIL:
        token = await AuthService._emailLogin(account, secret)
        break
      case LOGIN_TYPE.USER_ACCOUNT:
        token = await AuthService._accountLogin(account, secret)
        break
      default:
        break
    }
    return token
  }
  static async _emailLogin(account, secret) {
    const user = await User.verifyEmailPassword(account, secret)
    // 这里说明已经成功验证用户信息，需要颁发token给用户
    // 需要根据用户的类别传入不同的权限值
    return Auth.genToken(user.id, Auth.USER)
  }
  static async _accountLogin(account, secret) {
    const user = await User.verifyAccount({ account, secret, field: 'account' })
    // 这里说明已经成功验证用户信息，需要颁发token给用户
    // 需要根据用户的类别传入不同的权限值
    return Auth.genToken(user.id, Auth.USER)
  }
}

module.exports = AuthService
